package org.softmed.rest.server.defaults.generation;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.softmed.filehandling.FileUtil;

public class DefaultAdminBuilder {

	static String defaultDatabaseDirectory = "defaults";
	static Map<String, String> sourceToDestination = new HashMap<String, String>();
	FileUtil util = new FileUtil();

	public DefaultAdminBuilder() {

	}

	public void setDefaultAdministrationDatabases() throws Throwable {
		File file = util.getFile(defaultDatabaseDirectory);
		if (file.exists() && file.isFile())
			throw new RuntimeException(
					"The name for the admin database directory "
							+ defaultDatabaseDirectory + " is already taken "
							+ file.getCanonicalPath());

		if (!file.exists())
			throw new RuntimeException(
					"No directory found with the administration database backups !!! "
							+ file.getCanonicalPath());

		File[] files = file.listFiles();

		for (File child : files) {
			String name = child.getName();
			String destination = sourceToDestination.get(name);
			if (destination == null) {
				System.err
						.println("The file "
								+ name
								+ " found in admin backup directory "
								+ defaultDatabaseDirectory
								+ " isn't used for reseting defaults !!! either you forgot to set the destination directory or it shouldn't be here.");
				continue;
			}

			if (!destination.endsWith("/"))
				destination += "/";

			destination += name;

			util.copyFile(child, util.getFile(destination));

		}

	}

	public static String getDefaultDatabaseDirectory() {
		return defaultDatabaseDirectory;
	}

	public static void setDefaultDatabaseDirectory(
			String defaultDatabaseDirectory) {
		DefaultAdminBuilder.defaultDatabaseDirectory = defaultDatabaseDirectory;
	}

	public static Map<String, String> getSourceToDestination() {
		return sourceToDestination;
	}

	public static void setSourceToDestination(
			Map<String, String> sourceToDestination) {
		DefaultAdminBuilder.sourceToDestination = sourceToDestination;
	}

}
